package com.zjeav.lingjiao.ui.music;


import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.maning.mndialoglibrary.MProgressDialog;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.adapter.MusicAdapter;
import com.zjeav.lingjiao.base.baseBean.BaseActivity;
import com.zjeav.lingjiao.base.baseBean.LocalMetadata;
import com.zjeav.lingjiao.base.baseBean.Result;
import com.zjeav.lingjiao.base.listener.CallBackTypeInteraction;
import com.zjeav.lingjiao.base.receiver.MusicPlayerReceiver;
import com.zjeav.lingjiao.base.tools.PlayerMSG;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.base.utils.ErrorUtils;
import com.zjeav.lingjiao.ui.book.BookDetailContract;
import com.zjeav.lingjiao.ui.lrc.impl.LrcView;
import com.zjeav.lingjiao.ui.presenter.BookPresenter;

import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MusicActivity extends BaseActivity implements View.OnClickListener, CallBackTypeInteraction,
        BookDetailContract.BookMetaCollectView {

    //mp3需要播放的数据
    public static List<LocalMetadata> mp3Infos;

    //收藏、
    private ImageView love_img;
    //播放按钮
    private ImageView MusicPlay;
    //下一首
    private ImageView MusicNext;
    //上一首
    private ImageView back_img;
    private ImageView MusicPrevious;
    private ImageView listImg;
    private LinearLayout ll_list;
    private RecyclerView rv_list;
    private TextView close_txt;
    //显示总时间
    private TextView MusicTime;
    //显示当前时间
    private TextView MusicCurrentTime;
    //显示歌曲名
    private TextView MusicTitle;
    // 自定义歌词视图
    public static LrcView lrcView;
    //进度条
    SeekBar seekBar;
    //广播
    MusicPlayerReceiver musicPlayerReceiver;
    //更新歌词的频率，每秒更新一次
    private int mPalyTimerDuration = 1000;
    //更新歌词的定时器
    private Timer mTimer;
    //更新歌词的定时任务
    private TimerTask mTask;
    private MusicAdapter musicAdapter;

    private BookPresenter bookPresenter;

    public static final String UPDATE_ACTION = "com.flashmusic.action.UPDATE_ACTION";  //更新动作
    public static final String CTL_ACTION = "com.flashmusic.action.CTL_ACTION";        //控制动作
    public static final String MUSIC_CURRENT = "com.flashmusic.action.MUSIC_CURRENT";  //音乐当前时间改变动作
    public static final String MUSIC_DURATION = "com.flashmusic.action.MUSIC_DURATION";//音乐播放长度改变动作
    public static final String MUSIC_PLAYING = "com.flashmusic.action.MUSIC_PLAYING";  //音乐正在播放动作
    public static final String REPEAT_ACTION = "com.flashmusic.action.REPEAT_ACTION";  //音乐重复播放动作
    public static final String SHUFFLE_ACTION = "com.flashmusic.action.RANDOM_ACTION";//音乐随机播放动作
    public static final String PLAY_STATUE = "com.flashmusic.action.PLAY_STATUE";      //更新播放状态

    //播放方式表识0表示顺序播放，1表示列表循环，2表示单曲循环，3表示随机，初始为顺序播放
    int playmodeflag = 0;
    //歌曲播放的位置,就能够获取位置
    int position;
    int currentTime;
    int duration;//总时间
    int type;

    // 正在播放
    private boolean isPlaying;

    //控制后台线程退出
    boolean playStatus = true;
    boolean isFavorites = false;
    int id = 0;

    //转换毫秒数为时间模式，一般都是分钟数，音乐文件
    public static String formatDuring(long mss) {
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.musicplay);

        //初始化控件
        InitView();

        //获得传过来的值
        Intent intent = getIntent();
        position = Integer.parseInt(intent.getStringExtra("position"));
        currentTime = getIntent().getIntExtra("currentTime", 0);
        type = getIntent().getIntExtra("type", 0);
        if (musicPlayerReceiver == null) {
            musicPlayerReceiver = new MusicPlayerReceiver();
            musicPlayerReceiver.setBRInteractionListener(this);
            musicPlayerReceiver.registerScreenActionReceiver(this);
        }
        bookPresenter = new BookPresenter(this);
        //设置响应事件
        MusicNext.setOnClickListener(this);
        MusicPrevious.setOnClickListener(this);
        MusicPlay.setOnClickListener(this);
        String title = MusicActivity.mp3Infos.get(position).getBookName() + "\n" + MusicActivity.mp3Infos.get(position).getTitle();
        MusicTitle.setText(title);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
        for (int i = 0; i < MusicActivity.mp3Infos.size(); i++) {
            if (position == i) {
                id = MusicActivity.mp3Infos.get(i).getId();
                isFavorites = MusicActivity.mp3Infos.get(i).isFavorites();
                if (isFavorites){
                    love_img.setImageDrawable(getResources().getDrawable(R.mipmap.love_selectimg));
                }else {
                    love_img.setImageDrawable(getResources().getDrawable(R.mipmap.paly_favorite_copy));
                }
                break;
            }
        }
        PlayMusic();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(musicPlayerReceiver);
        MusicActivity.lrcView.setLrc(null);
        stopLrcPlay();
        finish();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        MusicActivity.lrcView.setLrc(null);
        super.onNewIntent(intent);
    }

    //初始化控件
    void InitView() {
        musicAdapter = new MusicAdapter();
        MusicTitle = findViewById(R.id.title_txt);
        MusicPlay = (ImageView) findViewById(R.id.musicplay);
        MusicNext = (ImageView) findViewById(R.id.musicnext);
        love_img = findViewById(R.id.love_img);
        back_img = findViewById(R.id.back_img);
        listImg = findViewById(R.id.list_img);
        ll_list = findViewById(R.id.ll_list);
        rv_list = findViewById(R.id.rv_list);
        close_txt = findViewById(R.id.close_txt);
        close_txt.setOnClickListener(this);
        love_img.setOnClickListener(this);
        listImg.setOnClickListener(this);
        back_img.setOnClickListener(this);
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setAdapter(musicAdapter);
        MusicPrevious = (ImageView) findViewById(R.id.musicprevious);
        MusicTime = (TextView) findViewById(R.id.playtime);
        MusicCurrentTime = (TextView) findViewById(R.id.playcurrenttime);
        seekBar = (SeekBar) findViewById(R.id.MusicProgress);
        lrcView = (LrcView) findViewById(R.id.lrcShowView);
        musicAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                LocalMetadata localMetadata = (LocalMetadata) adapter.getItem(position);
                String title = localMetadata.getBookName() + "\n" + localMetadata.getTitle();
                MusicTitle.setText(title);
                PlayItemMusic(position);
                ll_list.setVisibility(View.GONE);
            }
        });

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.back_img:
                finish();
                break;
            case R.id.list_img:
                ll_list.setVisibility(View.VISIBLE);
                musicAdapter.replaceData(MusicActivity.mp3Infos);
                break;
            case R.id.love_img:
                if (isFavorites) {
                    isFavorites = false;
                    love_img.setImageDrawable(getResources().getDrawable(R.mipmap.paly_favorite_copy));
                    MProgressDialog.showProgress(this, "取消收藏");
                    bookPresenter.removeCollectBookMeta(id);
                } else {
                    isFavorites = true;
                    love_img.setImageDrawable(getResources().getDrawable(R.mipmap.love_selectimg));
                    MProgressDialog.showProgress(this, "收藏");
                    bookPresenter.collectBookMeta(id);
                }

                break;
            case R.id.close_txt:
                ll_list.setVisibility(View.GONE);
                break;
            case R.id.musicplay:
                if (isPlaying) {
                    MusicPlay.setImageDrawable(getResources().getDrawable(R.mipmap.paly_play, null));
                    intent.setClass(MusicActivity.this, MusicService.class);
                    intent.putExtra("MSG", PlayerMSG.MSG.PAUSE_MSG);
                    startService(intent);
                    isPlaying = false;
                    SharedPreferencesUtils.setParam(this, "position", position);

                } else {
                    MusicPlay.setImageDrawable(getResources().getDrawable(R.mipmap.paly_pause, null));
                    intent.setClass(MusicActivity.this, MusicService.class);
                    intent.putExtra("MSG", PlayerMSG.MSG.CONTINUE_MSG);
                    startService(intent);
                    isPlaying = true;
                    SharedPreferencesUtils.setParam(this, "position", position);

                }
                break;

            case R.id.musicnext:
                PlayNextMusic();
                break;
            case R.id.musicprevious:
                PlayPreviousMusic();
                break;

            default:
                break;
        }
    }


    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        //停止拖动事件
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            //手动调节进度
            // TODO Auto-generated method stub
            int progress = seekBar.getProgress();
            ChangeProgress(progress);
        }

        //数值改变事件
        @Override
        public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
            // TODO Auto-generated method stub
        }

        //开始拖动事件
        @Override
        public void onStartTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub
        }
    };

    public void ChangeProgress(int progress) {
        Intent intent = new Intent();
        intent.setClass(MusicActivity.this, MusicService.class);
        intent.putExtra("url", mp3Infos.get(position).getUrl());
        intent.putExtra("position", position);
        intent.putExtra("MSG", PlayerMSG.MSG.PROGRESS_CHANGE);
        intent.putExtra("progress", progress);
        startService(intent);
    }

    //播放音乐
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void PlayMusic() {
        isPlaying = true;

        MusicPlay.setImageDrawable(getResources().getDrawable(R.mipmap.paly_play, null));
        // 开始播放的时候为顺序播放
        currentTime = getIntent().getIntExtra("currentTime", 0);
        Intent intent = new Intent();

        if (type == 0 || (MusicActivity.mp3Infos.get(0).getBookid() == Integer.parseInt(SharedPreferencesUtils.getParam(this, "bookid", -1).toString()) && position == Integer.parseInt(SharedPreferencesUtils.getParam(this, "position", -1).toString()))) {
            if (currentTime == 0) {
                intent.setClass(MusicActivity.this, MusicService.class);
                intent.putExtra("url", mp3Infos.get(position).getUrl());
                intent.putExtra("position", position);
                intent.putExtra("MSG", PlayerMSG.MSG.PLAY_MSG);
                MusicService.mp3Infos = mp3Infos;
                startService(intent);
                SharedPreferencesUtils.setParam(this, "bookid", mp3Infos.get(position).getBookid());
                SharedPreferencesUtils.setParam(this, "position", position);
            } else {
                ChangeProgress(currentTime);
            }
        } else {
            intent.setClass(MusicActivity.this, MusicService.class);
            intent.putExtra("url", mp3Infos.get(position).getUrl());
            intent.putExtra("position", position);
            intent.putExtra("MSG", PlayerMSG.MSG.PLAY_MSG);
            MusicService.mp3Infos = mp3Infos;
            startService(intent);
            SharedPreferencesUtils.setParam(this, "bookid", mp3Infos.get(position).getBookid());
            SharedPreferencesUtils.setParam(this, "position", position);
        }


    }

    //播放上一首音乐
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void PlayPreviousMusic() {
        position = position - 1;
        //   MusicPlay.setImageDrawable(getResources().getDrawable(R.drawable.musicpause,null));

        if (position < 0) {
            position = mp3Infos.size() - 1;
        }
        currentTime = 0;
        LocalMetadata mp3Info = mp3Infos.get(position);

        Intent intent = new Intent();
        SharedPreferencesUtils.setParam(this, "bookid", mp3Infos.get(position).getBookid());
        SharedPreferencesUtils.setParam(this, "position", position);
        intent.setClass(MusicActivity.this, MusicService.class);
        intent.putExtra("url", mp3Info.getUrl());
        intent.putExtra("position", position);
        intent.putExtra("MSG", PlayerMSG.MSG.PRIVIOUS_MSG);
        startService(intent);
        isPlaying = true;

        MusicPlay.setImageDrawable(getResources().getDrawable(R.mipmap.paly_pause, null));
    }

    //播放下一首音乐
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void PlayNextMusic() {
        //判断是否是随机播放，因为随机播放设置后，playmodeflag变为-1了
        if (playmodeflag == -1) {
            Random random = new Random();
            position = random.nextInt(mp3Infos.size());
        } else
            position = position + 1;
        if (position >= mp3Infos.size())
            position = 0;
        currentTime = 0;
        LocalMetadata mp3Info = mp3Infos.get(position);
        SharedPreferencesUtils.setParam(this, "bookid", mp3Infos.get(position).getBookid());
        SharedPreferencesUtils.setParam(this, "position", position);
        Intent intent = new Intent();
        intent.setClass(MusicActivity.this, MusicService.class);
        Log.e("url", JSON.toJSONString(mp3Info));
        intent.putExtra("url", mp3Info.getUrl());
        intent.putExtra("position", position);
        intent.putExtra("MSG", PlayerMSG.MSG.NEXT_MSG);
        startService(intent);
        MusicPlay.setImageDrawable(getResources().getDrawable(R.mipmap.paly_pause, null));
        isPlaying = true;

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void PlayItemMusic(int position) {
        currentTime = 0;
        LocalMetadata mp3Info = mp3Infos.get(position);
        Intent intent = new Intent();
        intent.setClass(MusicActivity.this, MusicService.class);
        SharedPreferencesUtils.setParam(this, "bookid", mp3Infos.get(position).getBookid());
        SharedPreferencesUtils.setParam(this, "position", position);
        Log.e("url", JSON.toJSONString(mp3Info));
        intent.putExtra("url", mp3Info.getUrl());
        intent.putExtra("position", position);
        intent.putExtra("MSG", PlayerMSG.MSG.NEXT_MSG);
        startService(intent);
        MusicPlay.setImageDrawable(getResources().getDrawable(R.mipmap.paly_pause, null));
        isPlaying = true;
    }

    /**
     * 停止展示歌曲
     */
    public void stopLrcPlay() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    @Override
    public void callBackType(String action) {

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void callBackType(String action, Intent intent) {
        if (action.equals(MUSIC_CURRENT)) {
            currentTime = intent.getIntExtra("currentTime", -1);
            SharedPreferencesUtils.setParam(MusicActivity.this, "currentTime", currentTime);
            seekBar.setProgress(currentTime);
            MusicCurrentTime.setText(formatDuring(currentTime));

        } else if (action.equals(MUSIC_DURATION)) {
            if (mTimer == null) {
                mTimer = new Timer();
                mTask = new LrcTask();
                mTimer.scheduleAtFixedRate(mTask, 0, mPalyTimerDuration);
            }
            duration = intent.getIntExtra("duration", -1);
            //总时间更新
            MusicTime.setText(formatDuring(duration));
            seekBar.setMax(duration);

        } else if (action.equals(UPDATE_ACTION)) {
            position = intent.getIntExtra("position", -1);
            MusicTime.setText(formatDuring(mp3Infos.get(position).getDuration()));
//                currentTime = 0;
            seekBar.setMax(duration);

        } else if (action.equals(PLAY_STATUE)) {
            boolean playstatue = intent.getBooleanExtra("playstatue", true);
            if (playstatue) {
                MusicPlay.setImageDrawable(getResources().getDrawable(R.mipmap.paly_pause, null));
                isPlaying = true;
            } else {
                MusicPlay.setImageDrawable(getResources().getDrawable(R.mipmap.paly_play, null));
                isPlaying = false;
                stopLrcPlay();
            }

        }
    }


    public void onDestroy() {
        //销毁activity时，要记得销毁线程
        playStatus = false;
        super.onDestroy();
    }

    @Override
    public void CollectSuccess(Result result) {
        MProgressDialog.dismissProgress();
        Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void RemoveCollect(Result result) {
        MProgressDialog.dismissProgress();
        Toast.makeText(this, "取消收藏成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void ShowError(Throwable throwable, String message) {
        Toast.makeText(this, ErrorUtils.showError(throwable, message), Toast.LENGTH_SHORT).show();
    }


    class LrcTask extends TimerTask {
        @Override
        public void run() {
            //获取歌曲播放的位置
//            final long timePassed = mPlayer.getCurrentPosition();
            MusicActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    //滚动歌词
                    lrcView.seekLrcToTime(currentTime);
                }
            });

        }
    }
}
